import { message } from 'antd';
import type { ChangeEvent, ClipboardEvent, CompositionEvent } from 'react';
import type { FormInstance } from 'antd/es/form';

// 定义字段类型
export type NumberField = 'phone' | 'money' | 'safe' | 'station' | 'between' | 'performance' | 'string' | 'password' | 'captcha' | 'username' | 'sort' | 'score' | 'stock'
|'price'|'originalPrice'|'freight'|'sold';

// 数字输入处理函数
export const handleNumberInput = (
    form: FormInstance,
    fieldName: NumberField,
    e: ChangeEvent<HTMLInputElement>,
    options: {
        supportDecimal?: boolean;
        isSalaryRange?: boolean;
    } = {}
) => {
    // 配置项默认值
    const { supportDecimal = true, isSalaryRange = false } = options;
    const input = e.target as HTMLInputElement;
    let value = input.value || '';

    // 跳过输入法组合过程
    if ((e.nativeEvent as any).isComposing) {
        return;
    }
    const cursorPosition = input.selectionStart || 0;
    // 数字过滤核心逻辑
    let filteredValue = value;
    if (isSalaryRange) {
        //仅保留数字和 "-"，并处理格式
        filteredValue = value
            .replace(/[^0-9-]/g, '')
            .replace(/-{2,}/g, '-')
            .replace(/^-/, '')
            .replace(/-(\d+)-/, '$1-');
    } else if (supportDecimal) {
        // 支持小数：仅保留数字和 "."，并处理格式
        filteredValue = value
            .replace(/[^\d.]/g, '')
            .replace(/^\./g, '')
            .replace(/\.{2,}/g, '.')
            .replace(/(\.\d{2}).+/g, '$1');
    } else {
        // 纯数字：仅保留数字
        filteredValue = value.replace(/\D/g, '');
    }
    // 最终值
    const finalValue = filteredValue;
    // 只有值变化时才更新
    if (finalValue !== value) {
        input.value = finalValue;
        form.setFieldsValue({ [fieldName]: finalValue });
        // 恢复光标位置
        setTimeout(() => {
            const newPosition = Math.max(0, Math.min(cursorPosition, finalValue.length));
            input.setSelectionRange(newPosition, newPosition);
        }, 0);
    }
};

// 密码输入处理函数
export const handlePasswordInput = (
    form: FormInstance,
    fieldName: string,
    e: ChangeEvent<HTMLInputElement>,
    options: {
        minLength?: number;
        maxLength?: number;
        allowLetters?: boolean;
        allowNumbers?: boolean;
        allowSpecialChars?: string;
    } = {}
) => {
    // 配置项默认值
    const {
        maxLength = 20,
        allowLetters = true,
        allowNumbers = true,
        allowSpecialChars = ''
    } = options;
    const input = e.target as HTMLInputElement;
    let value = input.value || '';
    // 跳过输入法组合过程
    if ((e.nativeEvent as any).isComposing) {
        return;
    }
    const cursorPosition = input.selectionStart || 0;
    // 密码过滤核心逻辑
    let filteredValue = value;
    // 1. 先移除所有空格
    filteredValue = filteredValue.replace(/\s/g, '');
    // 2. 构建允许的字符正则
    let allowedChars = '';
    if (allowLetters) allowedChars += 'a-zA-Z';
    if (allowNumbers) allowedChars += '0-9';
    // 对特殊字符转义，避免正则语法错误
    const escapedSpecialChars = allowSpecialChars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const allowRegex = new RegExp(`[^${allowedChars}${escapedSpecialChars}]`, 'g');
    // 3. 过滤不允许的字符
    filteredValue = filteredValue.replace(allowRegex, '');
    // 4. 限制最大长度
    filteredValue = filteredValue.slice(0, maxLength);
    // 最终值
    const finalValue = filteredValue;
    // 只有值变化时才更新
    if (finalValue !== value) {
        input.value = finalValue;
        form.setFieldsValue({ [fieldName]: finalValue });
        // 恢复光标位置
        setTimeout(() => {
            const newPosition = Math.max(0, Math.min(cursorPosition, finalValue.length));
            input.setSelectionRange(newPosition, newPosition);
        }, 0);
    }
};



// 中文输入处理函数
export const handleTextOnlyInput = (
    form: FormInstance,
    fieldName: string,
    e: ChangeEvent<HTMLInputElement>,
    options: {
        maxLength?: number;
    } = {}
) => {
    const { maxLength = 10 } = options;
    const input = e.target as HTMLInputElement;
    let value = input.value || '';
    // 跳过输入法组合过程中的输入
    if ((e.nativeEvent as any).isComposing) {
        return;
    }
    const cursorPosition = input.selectionStart || 0;
    // 只保留中文
    const chineseRegex = /[^\u4e00-\u9fa5]/g;
    const filteredValue = value.replace(chineseRegex, '');
    const finalValue = filteredValue.slice(0, maxLength);

    if (finalValue !== value) {
        input.value = finalValue;
        form.setFieldsValue({ [fieldName]: finalValue });

        // 恢复光标位置
        setTimeout(() => {
            const newPosition = Math.max(0, Math.min(cursorPosition, finalValue.length));
            input.setSelectionRange(newPosition, newPosition);
        }, 0);
    }
};

// 快捷方法：严格密码规则
export const handleStrictPasswordInput = (
    form: FormInstance,
    fieldName: string,
    e: ChangeEvent<HTMLInputElement> | ClipboardEvent<HTMLInputElement>
) => {
    return handlePasswordInput(form, fieldName, e, {
        minLength: 8,
        maxLength: 20,
        allowLetters: true,
        allowNumbers: true,
        allowSpecialChars: '' // 空字符串表示不允许任何特殊符号
    });
};

// 快捷方法：纯字母数字密码
export const handleAlphanumericPasswordInput = (
    form: FormInstance,
    fieldName: string,
    e: ChangeEvent<HTMLInputElement> | ClipboardEvent<HTMLInputElement>
) => {
    return handlePasswordInput(form, fieldName, e, {
        minLength: 6,
        maxLength: 20,
        allowLetters: true,
        allowNumbers: true,
        allowSpecialChars: '' // 不允许任何特殊符号
    });
};

// 使用示例 Hook
export const useInputHandlers = () => {
    const handleInputWithComposition = (
        handler: Function,
        form: FormInstance,
        fieldName: string,
        e: any,
        options?: any
    ) => {
        handler(form, fieldName, e, options);
    };

    return {
        handleInputWithComposition
    };
};

export type { NumberField };